// app.js
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


module.exports = app => {
    app.beforeStart(async () => {
      // 应用会等待这个函数执行完成才启动


      db_init(app);



      // 也可以通过以下方式来调用 Service
      // const ctx = app.createAnonymousContext();
      // app.cities = await ctx.service.cities.load();

      app.lodash =  require('lodash');

      //view/meun页面使用的判断菜单是否有权限可见的方法
      app.hasAuth = function(path,ctx){
         return ctx.session.user_info.auth.some((item,i)=>{
              return app.lodash.startsWith(path,item.path);
          })
      };




      //消息队列中间件 用于安全并发要求高的 资金账户处理
      var kue = require('kue');


      app.mainq = kue.createQueue({
        prefix: 'mainq',
        redis: {
                port: app.config.redis.client.port,
                host: app.config.redis.client.host,
                auth: app.config.redis.client.password,
                db: 2, // if provided select a non-default redis db
                options: {

                }
            }
       });

      //job 顺序 ： 入队enqueue 处理process 完成complete
        //处理process 默认只支持同时处理一个
       app.mainq.process( 'email',  ( job, done ) => {
        console.info("++++++");
        console.info(job.data);

        done(null,"csc win")

       })

       app.mainq.on('job enqueue', function(id, type){
        console.log( 'Job %s got queued of type %s', id, type );
       }).on('job complete', function(id, result){
            console.info("job complete");
            console.info('当前进程ID：',id,' 当前结果：',result);
            kue.Job.get(id, function(err, job){
                if (err) return;
                job.remove(function(err){
                    if (err) throw err;
                    console.log('removed completed job #%d', job.id);
                });
            });
        });



        const ctx = app.createAnonymousContext();
        await ctx.helper.receiveQueueMsg();
        // await ctx.helper.receiveQueueMsgStaff();
        // await ctx.service.dict.list();



    });

    app.sessionStore = {
        async get(key) {
            const res = await app.redis.get(key);
            if (!res) return null;
            return JSON.parse(res);
        },

        async set(key, value, maxAge) {
            // maxAge not present means session cookies
            // we can't exactly know the maxAge and just set an appropriate value like one day
            if (!maxAge) maxAge = 10 * 60 * 1000;
            value = JSON.stringify(value);
            await app.redis.set(key, value, 'PX', maxAge);
        },

        async destroy(key) {
            await app.redis.del(key);
        },
    };
};




async function db_init(app){

    await app.model.sync(
        // {
        //     force:true
        // }

    )

}

